#include "dspSimulator/instruction/AND.h"

namespace dspsimulator {
    void AND::generate_ir(const std::shared_ptr<simulator::IRGenElement> &ir_gen_element) {
        std::shared_ptr<simulator::LLVMJit> llvm_jit = ir_gen_element->m_llvm_jit;
        RegIRCopy &reg_ir_copy = ir_gen_element->m_reg_ir_copy;
        std::shared_ptr<llvm::IRBuilder<>> ir_builder = llvm_jit->ir_builder();
        // AND .func imm32,src2,src3
        auto op1 = std::dynamic_pointer_cast<Immediate32>(m_op1);
        auto op2 = std::dynamic_pointer_cast<SingleReg>(m_op2);
        auto op3 = std::dynamic_pointer_cast<SingleReg>(m_op3);
        if (op1 && op2 && op3) {
            std::string src2_name = get_reg_name(op2->reg());
            llvm::Value *src2 = reg_ir_copy[src2_name];
            llvm::Value *result = ir_builder->CreateAnd(src2, ir_builder->getInt32(op1->data()));
            std::string dst_name = get_reg_name(op3->reg());
            llvm::Value *dst_reg_ptr = IRGenerator::get_global_value_ptr(llvm_jit, dst_name);
            ir_builder->CreateStore(result, dst_reg_ptr);
        }
    }

    std::string AND::to_string() const {
        return get_standard_condition(m_creg_z) + m_name + " " + get_function_unit_name(m_func_unit) + " " +
               m_op1->to_string() + "," + m_op2->to_string() + "," + m_op3->to_string();
    }

    std::shared_ptr<simulator::Instruction> AND::clone() const {
        return std::make_shared<AND>(*this);
    }

    std::shared_ptr<DspInstruction> AND::decode_standard_instruction(const std::shared_ptr<DspInstructionInfo> &dsp_instruction_info) {
        std::shared_ptr<AND> _and;
        std::bitset<32> &data = dsp_instruction_info->m_standard_bits;
        if (common::check_bits<10>(data, 0b1001111100, 2) &&
            exist_standard_condition(common::extract_bits<4>(data, 28))) {
            // Opcode for .D Unit, 2 src   scst5,xop2,dst
            _and = std::make_shared<AND>(dsp_instruction_info->address(), 4);
            _and->m_creg_z = common::extract_bits<4>(data, 28);
            u32 dst = common::extract_bits<5>(data, 23).to_ulong();
            u32 src2 = common::extract_bits<5>(data, 18).to_ulong();
            u32 cst = common::extract_bits<5>(data, 13).to_ulong();
            bool x = data[12];
            bool s = data[1];
            _and->m_func_unit = s ? FuncUnit::D1 : FuncUnit::D2;
            _and->m_op1 = std::make_shared<Immediate32>(common::extract_bit_to_int<5>(cst));
            _and->m_op2 = std::make_shared<SingleReg>(get_src2_reg32_kind(src2, s, x));
            _and->m_op3 = std::make_shared<SingleReg>(get_dst_reg32_kind(dst, s));
            _and->m_p = data[0];
        }
        return _and;
    }
}